package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;

public class DateType implements TypeHandler<Date> {
    public Date get(ResultSet rs, String colName) throws SQLException {
        return rs.getDate(colName);
    }

    public Date get(ResultSet rs, int index) throws SQLException {
        return rs.getDate(index);
    }

    public Date get(CallableStatement rs, int index) throws SQLException {
        return rs.getDate(index);
    }

    @Override
    public Date get(CallableStatement cs, String parameterName) throws SQLException {
        return cs.getDate(parameterName);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        rs.updateDate(columnLabel, changeDateType(value));
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        rs.updateDate(columnIndex, changeDateType(value));
    }

    public Object set(PreparedStatement stat, Object value, int i) throws SQLException {
        if (null == value) {
            stat.setNull(i, getSqlType());
        } else {
            stat.setDate(i, changeDateType(value));
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object value, String parameterName) throws SQLException {
        if (null == value) {
            cs.setNull(parameterName, getSqlType());
        } else {
            cs.setDate(parameterName, changeDateType(value));
        }
        return null;
    }

    @Override
    public int getSqlType() {
        return Types.DATE;
    }

    @Override
    public Class<Date> getDefaultJavaType() {
        return Date.class;
    }

    private static java.sql.Date changeDateType(Object value) {
        if (java.sql.Date.class.isAssignableFrom(value.getClass())) {
            return (java.sql.Date) value;
        } else if (Date.class.isAssignableFrom(value.getClass())) {
            return new java.sql.Date(((Date) value).getTime());
        }if (Number.class.isAssignableFrom(value.getClass())) {
            return new java.sql.Date(((Number) value).longValue());
        }
        return null;
    }
}
